<template>
    <ElDialog v-model="dialogVisible" width="600px" :title="title">
        <UiForm :formData="formData" @close="dialogVisible = false" @callback="submitForm">
            <div class="has">
                <span>授权：</span>
                <el-tree :data="menuList" :props="menuListTreeProps" node-key="menuId" ref="menuListTree" show-checkbox></el-tree>
            </div>
        </UiForm>
    </ElDialog>
</template>
<script setup>
import {ElDialog, ElMessage, ElTree } from 'element-plus'
import UiForm from '@/components/uiForm.vue'
import { computed, ref, reactive, onMounted } from 'vue';
import {setRole, getMenus, getRoleInfo} from '@/server/manage/sys.js'
import { treeDataTranslate } from '@/utils'
const menuListTree = ref()
const props = defineProps(['modelValue', 'type', 'info'])
const emit = defineEmits(['update:modelValue', 'callback'])
const menuListTreeProps = { label: 'name', children: 'children'}
const menuList = ref([])
const tempKey = -666666
const formData = reactive([
    {label: "角色名称", type: 'input',key: "roleName", value: '', required: true},
    {label: "备注", type: 'input', widgetType: "textarea", key: "remark", value: '', required: false},
])
const dialogVisible = computed({
    set:(val) => {
        emit('update:modelValue', val)
    },
    get:() => {
        return props.modelValue
    }
})
const title = computed(() => {
    let obj = {add: '新增',edit: '编辑' }
    return obj[props.type]
})
// 提交
const submitForm = (formData) => {
    let obj = {add: 'save',edit: 'update' }
    let apiData = formData
    apiData.roleId = props.info?.roleId || undefined
    apiData.menuIdList = [].concat(menuListTree.value.getCheckedKeys(), [tempKey], menuListTree.value.getHalfCheckedKeys())
    setRole(apiData, obj[props.type]).then(res => {
        dialogVisible.value = false
        emit('callback')
        ElMessage({ message: "操作成功！", type: 'success'})
    })
}
// 获取详情
const getDetail = () => {
    getRoleInfo(props.info?.roleId).then(res => {
        console.log(res.role);
        let roleInfo = res.role
        let list = ['roleName', 'remark']
        formData.forEach(item => {
            if(list.includes(item.key)){
                item.value = roleInfo[item.key]
            }
        })
        var idx = roleInfo.menuIdList.indexOf(tempKey)
        if (idx !== -1) {
            roleInfo.menuIdList.splice(idx, roleInfo.menuIdList.length - idx)
        }
        menuListTree.value.setCheckedKeys(roleInfo.menuIdList)
    })
}
// 获取角色列表
const getRoles = async() => {
    getMenus().then(res => {
        menuList.value = treeDataTranslate(res, 'menuId')
        return Promise.resolve()
    })
}
onMounted(async() => {
    await getRoles()
    if(props.type === 'edit') {getDetail()}
})
</script>
<style scoped>
.has{
    width: 460px;
    margin: 20px auto;
    display: flex;
}
</style>